<template>
  <!-- 登录组件 -->
  <div class="loginContainer">
    <div class="loginWrap">
      <!-- 头像区域 -->
      <div class="avatar">
        <img src="../assets/images/logo.png" />
      </div>
      <!-- 表单登录区域 -->
      <el-form :model="loginInfo" ref="loginForm" :rules="rules">
        <el-form-item prop="username">
          <el-input
            clearable
            paceholder="请输入用户名"
            prefix-icon="el-icon-user"
            v-model="loginInfo.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            show-password
            clearable
            paceholder="请输入密码"
            prefix-icon="el-icon-lock"
            v-model="loginInfo.password"
          ></el-input>
        </el-form-item>
        <el-form-item align="right">
          <el-button type="primary" @click="submitForm">登录</el-button>
          <el-button type="info" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginInfo: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [{ required: true, message: '请输入用户名' }],
        password: [
          { required: true, message: '请输入密码' },
          { min: 6, max: 15, message: '密码长度必须5-16之间' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      // 登录
      this.$refs['loginForm'].validate(async valid => {
        if (valid) {
          // 表单验证通过
          const { data: res } = await this.$axios.post('login', {
            ...this.loginInfo
          })
          // 登录成功
          if (res && res.meta.status === 200) {
            // 提示登录成功
            this.$message({
              type: 'success',
              message: '登录成功'
            })
            // 将token保存到本地会话存储
            window.sessionStorage.setItem('token', res.data.token)
            // 跳转到首页
            this.$router.push('/')
          }
        } else {
          console.log('commit error')
          return false
        }
      })
    },
    resetForm() {
      // 重置
      this.$refs['loginForm'].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.loginContainer {
  height: 100%;
  background: rgb(43, 75, 107);
}
.loginWrap {
  width: 450px;
  height: 300px;
  position: fixed;
  background: #fff;
  padding: 20px;
  border-radius: 6px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  .avatar {
    position: absolute;
    box-sizing: border-box;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
    top: 0;
    left: 50%;
    border: 10px solid #fff;
    transform: translate(-50%, -50%);
    overflow: hidden;
    z-index: 999;
    background: #eee;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .el-form {
    position: absolute;
    bottom: 0;
    width: calc(100% - 40px);
  }
}
</style>
